package org.tiny.autounit.core.data.transport.server.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.tiny.autounit.core.data.transport.server.domain.MessageType;
import org.tiny.autounit.core.data.transport.server.domain.NettyMessage;

/**
 * @author shichaoyang
 * @Description: 心跳包helper
 * @date 2019-03-29 16:06
 */
public class HeartBeatHelper {

    /**
     * 心跳包构建
     * @return
     */
    public static NettyMessage buildHeartBeat() {
        NettyMessage message = new NettyMessage();
        message.setType(MessageType.HEARTBEAT.value());
        return message;
    }

    /**
     * 处理idleState事件
     * @param ctx
     * @param evt
     * @param readIdle
     * @param writeIdle
     * @param allIdle
     */
    public static void processIdleEvent(ChannelHandlerContext ctx, Object evt
            , Runnable readIdle
            , Runnable writeIdle
            , Runnable allIdle) {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                if (readIdle != null) {
                    readIdle.run();
                }
            } else if (event.state() == IdleState.WRITER_IDLE) {
                if (writeIdle != null) {
                    writeIdle.run();
                }
            } else if (event.state() == IdleState.ALL_IDLE) {
                if (allIdle != null) {
                    allIdle.run();
                }
            }
        }
    }

}
